package com.sy.olddriver.utils;

import org.apache.commons.lang.ArrayUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

public class CookieUtils {
    private CookieUtils() {

    }

    public static void addCookie(String name, String value, HttpServletResponse res) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        res.addCookie(cookie);
    }

    public static String getCookie(String name, HttpServletRequest req) {
        Cookie[] cookies = req.getCookies();
        if (!ArrayUtils.isEmpty(cookies)) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    public static void deleteCookie(String name, HttpServletRequest req, HttpServletResponse res) {
        System.out.println(name);
        Cookie[] cookies = req.getCookies();
        if (!ArrayUtils.isEmpty(cookies)) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    cookie.setPath("/");
                    cookie.setMaxAge(0);
                    res.addCookie(cookie);
                }
            }
        }
    }
}
